package com.example.maggie.meizinote.mvp.presenter;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.EditText;

import com.example.maggie.meizinote.R;
import com.example.maggie.meizinote.app.utils.HtmlUtils;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.sunflower.FlowerCollector;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.example.maggie.meizinote.mvp.contract.NoteTTSContract;

import static android.content.Context.MODE_PRIVATE;


@ActivityScope
public class NoteTTSPresenter extends BasePresenter<NoteTTSContract.Model, NoteTTSContract.View> implements InitListener, SynthesizerListener {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    public static final String PREFER_NAME = "com.iflytek.setting";
    private SharedPreferences mSharedPreferences;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    // 默认发音人
    private String voicer = "xiaoyan";

    // 语音合成对象
    private SpeechSynthesizer mTts;


    private String[] mCloudVoicersEntries;
    private String[] mCloudVoicersValue;
    private int selectedNum = 0;

    @Inject
    public NoteTTSPresenter(NoteTTSContract.Model model, NoteTTSContract.View rootView) {
        super(model, rootView);
    }

    public void changePersent(int num, String persent) {
        selectedNum = num;
        voicer = persent;
        if (mTts != null)
            mTts.stopSpeaking();
        isTTSSuccess = false;
        mRootView.setPlayType(false);
    }

    public void selectPersent() {
        mRootView.selectPersent(mCloudVoicersValue, mCloudVoicersEntries, selectedNum);
    }

    public void initTTS(Context context) {
        mTts = SpeechSynthesizer.createSynthesizer(context, this);
        // 云端发音人名称列表
        mCloudVoicersEntries = context.getResources().getStringArray(R.array.voicer_cloud_entries);
        mCloudVoicersValue = context.getResources().getStringArray(R.array.voicer_cloud_values);

        mSharedPreferences = context.getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
    }

    private boolean isTTSSuccess = false;

    public void play(String content, boolean isPlay) {
        if (isPlay) {//播放
            if (isTTSSuccess) mTts.resumeSpeaking();
            else play(content);
        } else //暂停
            pause();
    }

    public void pause() {
        mTts.pauseSpeaking();
    }


    public void play(String text) {
        if (null == mTts) {
            // 创建单例失败，与 21001 错误为同样原因，参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
            mRootView.showMessage("创建对象失败，请确认 libmsc.so 放置正确，且有调用 createUtility 进行初始化");
            return;
        }
        isTTSSuccess = true;
        // 移动数据分析，收集开始合成事件
        FlowerCollector.onEvent(mApplication, "tts_play");
        // 设置参数
        setParam();
        int code = mTts.startSpeaking(HtmlUtils.delHTMLTag(text), this);
//			/**
//			 * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
//			 * text:要合成的文本，uri:需要保存的音频全路径，listener:回调接口
//			*/
//			String path = Environment.getExternalStorageDirectory()+"/tts.ico";
//			int code = mTts.synthesizeToUri(text, path, mTtsListener);

        if (code != ErrorCode.SUCCESS) {
            mRootView.showMessage("语音合成失败,错误码: " + code);
        }
    }

    /**
     * 参数设置
     *
     * @return
     */
    private void setParam() {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 根据合成引擎设置相应参数
        if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50"));
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50"));
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50"));
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
            /**
             * TODO 本地合成不设置语速、音调、音量，默认使用语记设置
             * 开发者如需自定义参数，请参考在线合成参数设置
             */
        }
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3"));
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        if (mTts != null)
            mTts.stopSpeaking();
    }


    @Override
    public void onInit(int code) {
        Log.d(TAG, "InitListener init() code = " + code);
        if (code != ErrorCode.SUCCESS) {
            mRootView.showMessage("初始化失败,错误码：" + code);
        } else {
            // 初始化成功，之后可以调用startSpeaking方法
            // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
            // 正确的做法是将onCreate中的startSpeaking调用移至这里
        }
    }

    @Override
    public void onSpeakBegin() {
        mRootView.showMessage("开始播放");
//        mRootView.setPlayType();
    }

    @Override
    public void onSpeakPaused() {
        mRootView.showMessage("暂停播放");
//        mRootView.setPlayType(false);
    }

    @Override
    public void onSpeakResumed() {
        mRootView.showMessage("继续播放");
//        mRootView.setPlayType(true);
    }

    @Override
    public void onBufferProgress(int percent, int beginPos, int endPos,
                                 String info) {
        // 合成进度
//        mPercentForBuffering = percent;
//        mRootView.showMessage(String.format(getString(R.string.tts_toast_format),
//                mPercentForBuffering, mPercentForPlaying));
    }

    @Override
    public void onSpeakProgress(int percent, int beginPos, int endPos) {
        // 播放进度
//        mPercentForPlaying = percent;
//        showTip(String.format(getString(R.string.tts_toast_format),
//                mPercentForBuffering, mPercentForPlaying));
    }

    @Override
    public void onCompleted(SpeechError error) {
        if (error == null) {
            mRootView.showMessage("播放完成");
        } else if (error != null) {
            mRootView.showMessage(error.getPlainDescription(true));
        }
        mTts.stopSpeaking();
        isTTSSuccess = false;
        mRootView.setPlayType(false);
    }

    @Override
    public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
        // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
        // 若使用本地能力，会话id为null
        //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
        //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
        //		Log.d(TAG, "session id =" + sid);
        //	}
    }
}
